import IntegrationTable, {
	IntegrationTableProps,
} from "@/components/IntegrationTable";
import { ProColumns } from "@ant-design/pro-table";
import React, { useEffect, useState } from "react";
import {
	Image,
	message,
	Select,
	Button,
	Card,
	Tag,
	Tabs,
	DatePicker,
	Cascader,
} from "antd";
import { areaList, managerList, regenerant, regionData } from "./service";
import { DynamicFormItem } from "@/components/DynamicForm";
import type { TableListItem } from "./data";
import axios from "axios";
import { arrayToObject, getArray, getString, getObject } from "phinney-toolkit";
import moment from "moment";
const CommunityMan: React.FC<any> = () => {
	// 组件是否已经卸载
	let isUnMounted = false;

	const labelType = [
		{ label: "奖品领取", value: "10" },
		{ label: "收发快递", value: "20" },
	];

	let [area, setArea] = useState<any>([]);
	let [manager, setManager] = useState<any>([]);
	let [regenerantList, setRegenerantList] = useState<any>([]);
	let [regionList, setRegionList] = useState<any>([]);
	let [level, setLevel] = useState<any>(4);
	let [parentId, setParentId] = useState<any>("4101");
	const [defaultValue, setDefaultValue] = useState([]);

	const getAreaList = async () => {
		const res = await areaList({
			cityCode: "410100",
			pageIndex: "1",
			pageSize: "99",
		});
		!isUnMounted &&
			setArea(
				getArray(res?.data.records).map((item) => ({
					label: item?.areaName,
					value: item?.areaCode,
				}))
			);
	};
	//区域列表
	const getRegionList = async () => {
		const res = await regionData({
			pageIndex: 1,
			pageSize: 99,
			parentId,
		});

		console.log(res, "->>>res");
		!isUnMounted &&
			setRegionList(
				getArray(res?.data.records).map((item) => ({
					label: item?.regionName,
					value: item?.regionId,
				}))
			);
	};

	const getManager = async () => {
		const res = await managerList({
			pageIndex: "1",
			pageSize: "20",
			businessStatus: "1",
			managerStatus: "1",
		});
		!isUnMounted &&
			setManager(
				getArray(res?.data.records).map((item) => ({
					label: item?.communityName,
					value: item?.communityCode,
				}))
			);
	};

	const getRegenerantList = async () => {
		const res = await regenerant({
			pageIndex: "1",
			pageSize: "99",
		});
		!isUnMounted &&
			setRegenerantList(
				getArray(res?.data.records).map((item) => ({
					label: item?.itemName,
					value: item?.itemCode,
				}))
			);
	};

	// 表格项
	const columns: ProColumns<TableListItem>[] = [
		{
			title: "序号",
			dataIndex: "id",
			search: false,
		},
		{
			title: "小区code",
			dataIndex: "communityCode",
			search: false,
		},
		{
			title: "小区名称",
			dataIndex: "communityName",
			search: false,
		},
		{
			title: "小区图片",
			dataIndex: "communityCode",
			search: false,
			render: (_, record: any) => {
				if (record.communityImage) {
					return (
						<Image.PreviewGroup>
							<Image
								src={record.communityImage}
								style={{ padding: 8 }}
								width={50}
								alt=""
							/>
						</Image.PreviewGroup>
					);
				} else {
					return <div>-</div>;
				}
			},
		},
		{
			title: "经纬度",
			dataIndex: "communityName",
			render: (_, record: any) => {
				return record.lat + "," + record.lon;
			},
		},
		{
			title: "详细地址",
			dataIndex: "communityAddress",
			search: false,
			render: (_, record: any) => {
				return (
					<div>
						{" "}
						{record.provinceName} - {record.cityName} -{" "}
						{record.communityAddress}
					</div>
				);
			},
		},
		{
			title: "管理人名称",
			dataIndex: "managerName",
			search: false,
		},
		{
			title: "管理人角色",
			dataIndex: "managerStatus",
			valueEnum: {
				1: "组长",
				0: "-",
			},
			search: false,
		},
	];

	//显示/隐藏浮层的回调
	const onPopupVisibleChange = (value: any) => {
		console.log(value);
		// if (!props.value || (props.type === 'edit' && value)) {
		//   getOptions(categoryId);
		// }
	};
	//点击目录事件
	const regionChange = async (value: any, selectedOptions: any) => {};
	const getFormItems = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		const { coupon } = vm.state;
		return [
			{
				type: "select",
				label: "区域",
				name: "areaCode",
				options: area,
				required: true,
			},
			{
				type: "custom",
				label: "社区",
				name: "regionId",
				required: true,
				render: (form: any, formValues: any) => {
					return (
						<div>
							<Cascader
								options={regionList}
								changeOnSelect
								defaultValue={[formValues.regionName] || ""}
								onChange={async (value: any, selectedOptions: any) => {
									const targetOption =
										selectedOptions[selectedOptions.length - 1];
									let selectParentId =
										selectedOptions[selectedOptions.length - 1].value;
									if (selectedOptions[2]) {
										form.setFieldsValue({
											regionId: selectParentId,
										});
										return;
									}
									const res = await regionData({
										pageIndex: "1",
										pageSize: "99",
										parentId: selectParentId,
									});
									const newData: any = [];
									res.data.records.map((item: any) => {
										return newData.push({
											label: item?.regionName,
											value: item?.regionId,
										});
									});
									targetOption.children = newData;
									setDefaultValue(value);
								}}
								onPopupVisibleChange={onPopupVisibleChange}
								allowClear={false}
							/>
						</div>
					);
				},
			},
			{
				type: "custom",
				label: "小区名称",
				name: "communityName",
				required: true,
				render: (form: any, formValues: any) => {
					console.log(form, formValues, "->>>formValues");
					return (
						<div style={{ width: "100%" }}>
							<Select
								id="Community"
								showSearch
								placeholder="请输入小区名称"
								showArrow={false}
								filterOption={false}
								defaultValue={formValues.communityName || ""}
								optionLabelProp="label"
								onSearch={(value: any) => {
									let isAreaCode = form.getFieldValue("areaCode");
									if (!isAreaCode) {
										message.error("请选择区域!");
										return false;
									} else {
										axios
											.get(
												`https://restapi.amap.com/v3/place/text?key=10c01e3af3272d167f7ab9880eb137c5&types=120000&keywords=${value}&city=${isAreaCode}&extensions=all`
											)
											.then((response) => {
												let result = response.data.pois;
												vm.setState({
													community: result,
												});
											});
									}
								}}
								onChange={(value: any, option: any) => {
									console.log(option);
									let location = option.location.split(",");
									form.setFieldsValue({
										communityCode: option.key,
										communityAddress: option.address,
										lon: location[0],
										lat: location[1],
										communityName: option.value,
									});

									console.log(form.getFieldValue("communityCode"));
								}}
							>
								{getArray(vm.state.community).map((item: any) => {
									return (
										<Select.Option
											key={item.id}
											value={item.name}
											location={item.location}
											address={item.address}
										>
											{item.name}
										</Select.Option>
									);
								})}
							</Select>
						</div>
					);
				},
			},
			{
				type: "text",
				label: "小区code",
				name: "communityCode",
				required: true,
			},
			{
				type: "textarea",
				label: "详细地址",
				name: "communityAddress",
				required: true,
			},
			{
				type: "upload",
				label: "上传图标",
				name: "communityImage",
				fieldProps: {
					limit: 1,
				},
			},
			{
				type: "text",
				label: "楼栋",
				name: "communityBuildingNum",
			},

			{
				type: "text",
				label: "多少户",
				name: "communityPeopleNum",
			},
			{
				type: "text",
				label: "经度",
				name: "lon",
				required: true,
			},
			{
				type: "text",
				label: "纬度",
				name: "lat",
				required: true,
			},
			{
				type: "select",
				label: "小区组长",
				name: "managerCode",
				options: manager,
			},
			{
				type: "upload",
				label: "小区二维码",
				name: "qrCodeUrl",
				fieldProps: {
					limit: 1,
				},
			},
			{
				type: "select",
				label: "是否是小区组长",
				name: "managerStatus",
				required: true,
				options: [
					{
						label: "否",
						value: 0,
					},
					{
						label: "是",
						value: 1,
					},
				],
			},
			{
				type: "select",
				label: "是否开通业务",
				name: "businessStatus",
				required: true,
				options: [
					{
						label: "否",
						value: 0,
					},
					{
						label: "是",
						value: 1,
					},
				],
			},
			{
				type: "textarea",
				label: "围栏经纬度",
				name: "specShape",
			},
			{
				type: "text",
				label: "企业微信群id",
				name: "plugid",
			},
		];
	};

	const getFormItemsSend = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		const { coupon } = vm.state;
		return [
			{
				type: "custom",
				label: "回收时间",
				name: "recoverTime",
				required: true,
				render: (form: any, formValues: any) => {
					console.log(formValues.recoverTime, "-______formValues.recoverTime");
					return (
						<div style={{ width: "100%" }}>
							<DatePicker
								// defaultValue={moment()}
								style={{ width: 280 }}
								defaultValue={
									formValues.recoverTime
										? moment(formValues.recoverTime, "YYYY-MM-DD HH:mm:ss")
										: undefined
								}
								onChange={(value: any, option: any) => {
									form.setFieldsValue({
										recoverTime: option,
									});
								}}
								format="YYYY-MM-DD HH:mm:ss"
								showTime={{ defaultValue: moment("00:00:00", "HH:mm:ss") }}
							/>
						</div>
					);
				},
			},
			{
				type: "text",
				label: "回收物地址",
				name: "addressDetail",
				required: true,
			},
			{
				type: "select",
				label: "回收物",
				name: "itemCodes",
				options: regenerantList,
				required: true,
				fieldProps: {
					mode: "multiple",
				},
			},
		];
	};

	const getFormItemsSend2 = (vm: any, isEdit?: boolean): DynamicFormItem[] => {
		return [
			{
				type: "text",
				label: "社区点名字",
				name: "cooperateName",
				required: true,
			},
			{
				type: "text",
				label: "社区点地址",
				name: "addressDetail",
				required: true,
			},
			{
				type: "select",
				label: "label",
				name: "label",
				required: true,
				options: labelType,
				fieldProps: {
					mode: "multiple",
				},
			},
			{
				type: "upload",
				label: "社区点logo",
				name: "logo",
				required: true,
				fieldProps: {
					limit: 1,
				},
			},
		];
	};

	const columnss: ProColumns[] = [
		{
			title: "ID",
			dataIndex: "id",
			search: false,
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			search: false,
		},
		{
			title: "站点名字",
			dataIndex: "cooperateName",
		},
		{
			title: "地址",
			dataIndex: "addressDetail",
		},
		{
			title: "label",
			dataIndex: "labelName",
			search: false,
		},
		{
			title: "站点图片",
			dataIndex: "logo",
			search: false,
			render: (_, record: any) => {
				if (record.logo) {
					return (
						<Image.PreviewGroup>
							<Image
								src={record.logo}
								style={{ padding: 8 }}
								width={50}
								alt=""
							/>
						</Image.PreviewGroup>
					);
				} else {
					return <div>-</div>;
				}
			},
		},
	];

	const columnsss: ProColumns[] = [
		{
			title: "ID",
			dataIndex: "id",
			search: false,
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			search: false,
		},
		{
			title: "回收时间",
			dataIndex: "recoverTime",
			search: false,
		},
		// {
		// 	title: "定点回收code",
		// 	dataIndex: "recoverCode",
		// 	search: false,
		// },
		{
			title: "地址",
			dataIndex: "addressDetail",
			search: false,
		},
		{
			title: "回收物",
			dataIndex: "itemCodes",
			search: false,
			render: (_, record: any) => {
				return (
					<div>
						{record.itemList
							? record.itemList.map((item: any) => {
									return (
										<div style={{ marginBottom: 5 }}>
											<Tag color="processing">
												名称:{item.itemName} 价格:{item.itemPrice / 100} 单位:
												{item.itemUnit}
											</Tag>
										</div>
									);
							  })
							: "-"}
					</div>
				);
			},
		},
	];

	const handelFunc = (vm: any) => {
		let params = {
			rowKey: "id",
			scroll: { x: 1000 },
			columns: columnss,
			search: false,
			isInModal: true,
			// toolBarRender: false,
			toolbar: false,
			PageHeaderWrapper: false,
			listProps: {
				url: "/community-cooperate/community-cooperate-list",
				method: "GET",
				requestType: "params",
				formProps: {
					labelCol: { span: 4 },
				},
				paramsHandle: (params: any, record: any) => {
					return {
						...params,
						communityCode: vm.state.record.communityCode,
					};
				},
			},
			addProps: {
				url: "/community-cooperate/add",
				method: "POST",
				requestType: "params",
				formValuesHandle: (record: any) => {
					console.log(record, "-??????record");
					console.log(setParentId);
					const roleNames = getString(record?.label).split(",");
					const roleMap = arrayToObject(labelType, {
						label: "value",
						value: "label",
					});
					return {
						...record,
						label: roleNames.map((m) => roleMap[m]).filter(Boolean),
					};
				},
				paramsHandle: (params: any) => {
					console.log(setParentId);
					params.logo = (params?.logo?.map((item: any) => item.url) || []).join(
						","
					);
					return {
						...params,
						communityCode: vm.state.record.communityCode,
						communityName: vm.state.record.communityName,
					};
				},
				modalProps: {
					title: "添加小区社区",
					formProps: {
						labelCol: { span: 6 },
					},
					formItemsHandle: (_: any, vm: any) => {
						return getFormItemsSend2(vm);
					},
				},
			},
			updateProps: {
				url: "/community-cooperate/update-cooperate-id",
				method: "POST",
				modalProps: {
					formProps: {
						labelCol: { span: 6 },
					},
					title: "编辑小区社区",
					formItemsHandle: (_: any, vm: any) => {
						return getFormItemsSend2(vm, true);
					},
					formValuesHandle: (record: any) => {
						return {
							...record,
							logo: record.logo
								? [
										{
											uid: "-1",
											status: "done",
											name: record.logo,
											url: record.logo,
										},
								  ]
								: [],
							label: record.label.split(","),
						};
					},
				},
				paramsHandle: async (params: any) => {
					params.logo = (params?.logo?.map((item: any) => item.url) || []).join(
						","
					);
					return {
						...params,
						label: getArray(params.label).toString(),
					};
				},
			},
			deleteProps: {
				url: "/community-cooperate/delete-cooperate-id",
				method: "POST",
			},
		};
		let params2 = {
			rowKey: "id",
			scroll: { x: 1000 },
			columns: columnsss,
			search: false,
			isInModal: true,
			toolbar: false,
			PageHeaderWrapper: false,
			listProps: {
				url: "/recover/recover-list",
				method: "GET",
				requestType: "params",
				paramsHandle: (params: any, record: any) => {
					return {
						...params,
						communityCode: vm.state.record.communityCode,
					};
				},
			},
			addProps: {
				url: "/recover/add",
				method: "POST",
				requestType: "params",
				formValuesHandle: (record: any) => {
					return {
						...record,
					};
				},
				paramsHandle: (params: any) => {
					return {
						...params,
						communityCode: vm.state.record.communityCode,
						itemCodes: params?.itemCodes.join(","),
					};
				},

				modalProps: {
					formProps: {
						labelCol: { span: 8 },
					},
					title: "添加定点回收",
					formItemsHandle: (_: any, vm: any) => {
						return getFormItemsSend(vm);
					},
				},
			},
			updateProps: {
				url: "/recover/update-recover-id",
				method: "POST",
				modalProps: {
					title: "编辑定点回收",
					formProps: {
						labelCol: { span: 8 },
					},
					formItemsHandle: (_: any, vm: any) => {
						return getFormItemsSend(vm, true);
					},
					formValuesHandle: (record: any) => {
						return {
							...record,
							itemCodes: record.itemCodes.split(","),
						};
					},
				},
				paramsHandle: async (params: any) => {
					return {
						...params,
						itemCodes: params?.itemCodes.join(","),
					};
				},
			},

			deleteProps: {
				url: "/recover/delete-recover-id",
				method: "POST",
			},
		};
		return (
			<Tabs style={{ padding: 0 }}>
				<Tabs.TabPane tab="小区社区" key="1">
					<IntegrationTable {...params} />
				</Tabs.TabPane>
				<Tabs.TabPane tab="定点回收" key="2">
					<IntegrationTable {...params2} />
				</Tabs.TabPane>
			</Tabs>
		);
	};

	// 一体化表格props
	const tablePorps: IntegrationTableProps = {
		rowKey: "id",
		scroll: { x: 1000 },
		columns,
		listProps: {
			url: "/community/list",
			method: "GET",
			requestType: "params",
			paramsHandle: (params: any) => {
				return {
					...params,
					// businessStatus: 1,
				};
			},
		},
		addProps: {
			url: "/community/add",
			method: "POST",
			paramsHandle: (params: any) => {
				params.communityImage = (
					params?.communityImage?.map((item: any) => item.url) || []
				).join(",");
				params.qrCodeUrl = (
					params?.qrCodeUrl?.map((item: any) => item.url) || []
				).join(",");
				return {
					...params,
					provinceCode: "410000",
					provinceName: "河南省",
					cityName: "郑州市",
					cityCode: "410100",
					areaName: "",
				};
			},
			modalProps: {
				formValuesHandle: async (record: any, form: any) => {
					const { ...others } = record;

					console.log(form, "->>>>>form");
					return {
						...others,
						managerStatus: 0,
						businessStatus: 0,
					};
				},

				content: {},
				formProps: {
					labelCol: { span: 8 },
				},
				formItemsHandle: (_: any, vm: any) => {
					return getFormItems(vm);
				},
			},
		},
		updateProps: {
			url: "/community/edit",
			method: "POST",
			requestType: "params",

			paramsHandle: ({ ...params }: any, record: any) => {
				params.communityImage = (
					params?.communityImage?.map((item: any) => item.url) || []
				).join(",");

				params.qrCodeUrl = (
					params?.qrCodeUrl?.map((item: any) => item.url) || []
				).join(",");
				return {
					...params,
					provinceCode: "410000",
					provinceName: "河南省",
					cityName: "郑州市",
					cityCode: "410100",
					areaName: "",
				};
			},
			modalProps: {
				formValuesHandle: async (record: any, form: any) => {
					const { ...others } = record;
					return {
						...others,
						communityImage: others?.communityImage
							? [
									{
										uid: "-1",
										status: "done",
										name: others.communityImage,
										url: others.communityImage,
									},
							  ]
							: [],
						qrCodeUrl: others?.qrCodeUrl
							? [
									{
										uid: "-1",
										status: "done",
										name: others.qrCodeUrl,
										url: others.qrCodeUrl,
									},
							  ]
							: [],
					};
				},

				formProps: {
					labelCol: { span: 8 },
				},
				formItemsHandle: (_: any, vm: any) => {
					return getFormItems(vm, true);
				},
			},
		},
		handleOperating: (items: any[]) => [
			{
				type: "modal",
				props: {
					btnText: "设置",
					modalProps: {
						width: 1200,
						footer: false,
						title: "设置",
						content: {
							render: (vm: any, getModalRef: any) => {
								return handelFunc(vm);
							},
						},
						onCancel: (table: any) => {
							table?.reload();
						},
					},
					paramsHandle: ({ roleCode, status }: any, record: any) => ({
						userCode: record?.userCode,
						status,
						roleCodes: getArray(roleCode).toString(),
					}),
				},
			},
			...items,
		],
	};

	// 初始化加载数据
	useEffect(() => {
		getRegenerantList();
		getManager();
		getAreaList();
		getRegionList();
		return () => {
			isUnMounted = true;
		};
	}, []);

	return <IntegrationTable {...tablePorps} />;
};

export default CommunityMan;
